import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import store from './store.js'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      meta: {
        requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
      }
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
    },
    {
      path: '/login',
      name: 'login',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/Login.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  let token = store.state.token;
  let expTimeOut = store.state.expireTimeOut.valueOf();
  let curTime = new Date().valueOf();
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    if (token && token.length >= 128 && curTime < expTimeOut) {  // 通过vuex state获取当前的token是否存在
      next();
    }
    else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }  // 将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  }
  else {
    if (to.path == '/login' && token && token.length >= 128 && curTime < expTimeOut) {
      next({ path: '/' })
    } else {
      next();
    }

  }
})

export default router

//https://panjiachen.github.io/vue-element-admin-site/zh/guide/essentials/new-page.html#%E5%A4%9A%E7%BA%A7%E7%9B%AE%E5%BD%95-%E5%B5%8C%E5%A5%97%E8%B7%AF%E7%94%B1
//http://localhost:8080/#/